import {createRouter, createWebHashHistory} from 'vue-router'
import Layout from '../components/Layout/index.vue'

const routers = [
    {
        path: '/',
        redirect : "/main",
    },
    {
        path: '/login',
        name: 'Login',
        component:()=>import("../views/Login.vue"),
    },
    {
        path:'/main',
        component:Layout,
        redirect: '/home',
        children:[
            {
                path:"/home",
                name:"Home",
                component:()=>import("../views/Home.vue")
            }
        ]
    },
    {
        path:'/goods',
        name:'GoodsManager',
        component: Layout,
        children:[
            {
                path:"goods-list",
                name:"GoodList",
                component:()=>import("../views/GoodslistWithPopUpCard.vue")
            }
        ]
    },
    {
        path:'/user',
        name:'user manager',
        component: Layout,
        children:[
            {
                path:"user-list",
                name:"user_list",
                component:()=>import("../views/UserList.vue")
            },
            {
                path:"user-info",
                name:"user_info",
                component:()=>import("../views/GoodslistAxios.vue")
            }
        ]
    },
    {
        path:'/:pathMatch(.*)*',
        name:'404',
        component:()=>import("../views/NotFound.vue")
    }
];

const router = createRouter({
    history:createWebHashHistory(),
    routes:routers
});

router.beforeEach((to,from,next)=>{
    //to: will go
    //from: from where
    //next: function
    if(to.path == '/login')
    {
        return next();
    }
    
    const tokenStr = window.sessionStorage.getItem('token');
    //做校验，可以后端校验
    if(tokenStr)
    {
        console.log("send to backend to varify token");
        console.log(tokenStr);
        return next();
    }
    else
    {
        return next("/login");
    } 
})

export default router;